﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Models.ForeEndModels.UITasks;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Qin.Common;
using Quartz;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using HamcoWcs.Models.Common;

namespace HamcoWcs.Workers
{
    [DisallowConcurrentExecution]
    public class TaskBakWork : WorkerBase
    {
        public TaskBakWork(WcsDbContext wcsDbContext, IMapper mapper, ILoggerService logger) : base(wcsDbContext, mapper, logger)
        {
        }
        protected static string FILE_CONTENT_TYPE = "application/octet-stream";
        public override Task Execute(IJobExecutionContext context)
        {
            var firsttask = _wcsDbContext.MainTaskBaks.AsNoTracking().OrderBy(x => x.CreatedTime).FirstOrDefault();
            var time = firsttask.CreatedTime;
            if (time < DateTime.Now.AddDays(-90))
            {
                var year = time.Year;
                var month = time.Month;
                var day = time.Day;
                var startTime = new DateTime(year,month,day,0,0,0);
                var endTime = startTime.AddDays(1);
                var maintasks = _wcsDbContext.MainTaskBaks.Where(x => x.CreatedTime >= startTime && x.CreatedTime < endTime);
                var subTaskBaks = _wcsDbContext.SubTaskBaks.Where(x => x.CreatedTime >= startTime && x.CreatedTime < endTime);
                var data = _mapper.Map<List<UIMainTask>>(maintasks);
                var wb = new XSSFWorkbook();
                ISheet st = ExcelHelper.SetSheet(wb, data);

                var path = Path.Combine(GlobalValue.TaskLogFolder, $"{startTime:yyyyMMdd}historytask.xlsx");
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    wb.Write(fs);
                }
                var nfs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
                //return ControllerBase.File(nfs, FILE_CONTENT_TYPE, "export_maintask_history.xlsx");
                _wcsDbContext.SubTaskBaks.RemoveRange(subTaskBaks);
                _wcsDbContext.MainTaskBaks.RemoveRange(maintasks);
                _wcsDbContext.SaveChanges();
            }
            return Task.CompletedTask;
        }
    }
}
